package org.example.k8s_cloudplatform.interceptor;

import com.alibaba.fastjson.JSON;
import org.example.k8s_cloudplatform.entity.res.Result;
import org.example.k8s_cloudplatform.utils.JwtUtil;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    private final String[] white_urls = {
            "/user/login",
    };
    private final String[] manager_urls = {//管理员权限
            "/user/register",
            "/user/viewUser",
            "/user/findUserByID",
            "/user/delete",
            "/user/passwordReset",
            "/podRequest/viewUnprocessedRequest",
            "/podRequest/updateStatus",
            "/pod/viewActivePod"
    };

    private final String[] common_urls = {//普通权限
            "/user/info",
            "/user/updateInfo",
            "/user/updatePassword",
            "/pod/viewMyPod",
            "/pod/delete",
            "/pod/viewPodAccess",
            "/podRequest/request",
            "/podRequest/relet",
            "/podRequest/viewMyRequest",
            "/podAccess/viewUnauthorizedUser",
            "/podAccess/addAuthorizedUser",
            "/podAccess/viewPodAuthorization",
            "/podAccess/deleteAuthorizedUser",
    };

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, @NotNull Object o) throws Exception {
        String url = httpServletRequest.getRequestURI();
        String token = httpServletRequest.getHeader("Token");

        logger.info("Request URI: " + url);
        logger.info("User Token: " + token);

        for (String item : this.white_urls)
            if (item.equals(url))
                return true;

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");

        try {
            if (JwtUtil.outOfTime(token)) {
                outputStream.print(JSON.toJSONString(Result.tokenTimeOut()));
            } else {
                if (JwtUtil.jobChecker(token)==1) {//管理员
                    boolean flag = false;
                    for (String item : this.manager_urls)
                        if (item.equals(url)) {
                            flag = true;
                            break;
                        }
                    if (!flag) {
                        for (String item : this.common_urls)
                            if (item.equals(url)) {
                                flag = true;
                                break;
                            }
                    }
                    if (!flag) {
                        outputStream.print(JSON.toJSONString(Result.tokenError()));
                        return false;
                    } else {
                        return true;
                    }
                } else if (JwtUtil.jobChecker(token)==0) {//普通用户
                    boolean flag = false;
                    for (String item : this.common_urls)
                        if (item.equals(url)) {
                            flag = true;
                            break;
                        }
                    if (!flag) {//普通权限
                        outputStream.print(JSON.toJSONString(Result.tokenError()));
                        return false;
                    } else {
                        return true;
                    }
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            httpServletResponse.sendError(500);
            return false;
        }
    }
}
